package cn.picclife.mwx.manager.util.filter;

import cn.picclife.mwx.common.core.util.http.HttpUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import cn.picclife.mwx.common.web.filter.CorsUtil;
import cn.picclife.mwx.manager.sys.mapper.SysMaintainMapper;

/**
 * 处理跨域问题
 * @author 59238
 *
 */
@Component
public class SimpleCORSFilter implements Filter{
	
	private Log log = LogFactory.getLog(SimpleCORSFilter.class);

	@Override
	public void destroy() {
		
	}
	ApplicationContext ctx = null;
	@Autowired
	private SysMaintainMapper sysMaintainMapper;
	


	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {

		req.setCharacterEncoding("UTF-8");
		res.setCharacterEncoding("UTF-8");
		// 跨域不为空，表示未同域请求，则设置跨域信息
		// begin process cors
		HttpServletRequest request = (HttpServletRequest)req;
		String systemUrl = request.getHeader("Origin");
		log.info("接入系统systemUrl:" + systemUrl);
		HttpServletResponse response = (HttpServletResponse) res;
		CorsUtil corsUtil = new CorsUtil();
		if(sysMaintainMapper==null) {
			sysMaintainMapper = (SysMaintainMapper)ctx.getBean("sysMaintainMapper");
		}
		int count = sysMaintainMapper.queryCountBySystemurl(systemUrl);
		if(count<=0) {
	        chain.doFilter(req, res);
		    return;
		}
		if (corsUtil.isPreflight(req)) {
			log.info("================预检请求==========================");
			// 如果是cors preflight request则设置cors预检权限
			corsUtil.allowPreflightPermit(req, res);
			// 返回204状态
			((HttpServletResponse) res).setStatus(204);
			// 直接返回不做后续处理
			return;
		} else {
			log.info("=============");
			// 如果是cors actual request则设置相关cors权限
			corsUtil.allowActualPermit(req, res);
		}
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Allow-Headers", "DNT,x-auth-token,rqstSource,X-CustomHeader,Keep-Alive,User-Agent,"
				+ "X-Requested-With,If-Modified-Since,If-None-Match,Cache-Control,Content-Type,ASEKEY,TOKEN,TIME_STAMP,MD5_TOKEN,SYSTEM_CODE");//隋哥====
		response.setHeader("Access-Control-Max-Age", "3628800");//=======================20210108==========================================hsts
//		response.setHeader("Strict-Transport-Security","max-age=3628800; includeSubDomains");
//超哥========================================================================
		if (request.getMethod().equals("OPTIONS")) {
			response.setStatus(HttpStatus.OK.value());
			// hresp.setContentLength(0);
			response.getWriter().write("OPTIONS returns OK");
			return;
		}
		chain.doFilter(req, res);
	}


	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sc = filterConfig.getServletContext();
		ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
	}

}
